package com.leyou.cart.service.impl;

import com.leyou.auth.entity.UserInfo;
import com.leyou.cart.client.GoodsClient;
import com.leyou.cart.interceptor.LoginInterceptor;
import com.leyou.cart.pojo.Cart;
import com.leyou.cart.service.CartService;
import com.leyou.common.utils.JsonUtils;
import com.leyou.item.pojo.Sku;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private GoodsClient goodsClient;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public void addCart(Cart cart) {
        Integer num = cart.getNum();
        //先获取userinfo对象
        UserInfo userInfo = LoginInterceptor.get();
        //查询,获取操作hash的对象并绑定对应的key
        BoundHashOperations<String, String, String> hashOptions = redisTemplate.boundHashOps(userInfo.getId().toString());
        //判断是否有，有就更新，没就新增
        String skuId = cart.getSkuId().toString();
        if (hashOptions.hasKey(skuId)){
            //更新数量
            String cartJson = hashOptions.get(skuId).toString();
             cart = JsonUtils.parse(cartJson, Cart.class);
             cart.setNum(num+cart.getNum());
        }else {
            //新增
            cart.setUserId(userInfo.getId());
            //查询商品信息
            Sku sku = goodsClient.querySkuById(cart.getSkuId());
            cart.setImage(StringUtils.isBlank(sku.getImages()) ? "":StringUtils.split(sku.getImages(),",")[0]);
            cart.setOwnSpec(sku.getOwnSpec());
            cart.setTitle(sku.getTitle());
            cart.setPrice(sku.getPrice());
        }
        //把cart放入redis
        hashOptions.put(skuId,JsonUtils.serialize(cart));

    }

    @Override
    public List<Cart> QueryCarts() {
        UserInfo userInfo = LoginInterceptor.get();
        if (!redisTemplate.hasKey(userInfo.getId().toString())){
            return null;
        }
        BoundHashOperations<String, Object, Object> hashOperations = redisTemplate.boundHashOps(userInfo.getId().toString());
        List<Object> cartJsons = hashOperations.values();

        return cartJsons.stream().map(cartJson->
            JsonUtils.parse(cartJson.toString(),Cart.class)
        ).collect(Collectors.toList());
    }
}
